package com.waterstudio.filedownloader.ext.m3u8.utils;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;

/**
 * Created by chensuilun on 2017/9/26.
 */
public class FileUtils {


    public static String convertBytesToMB(long bytes) {
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        return decimalFormat.format(bytes / 1024.f / 1024.f);
    }

    /**
     * 统一获取raw文件流中数据
     *
     * @param context
     * @param rawId
     * @return
     */
    public static String getShortStrDataFromRaw(Context context, int rawId) {
        String strData = null;
        if (context == null) {
            return strData;
        }
        // 从资源获取流
        InputStream is = null;
        try {
            is = context.getResources().openRawResource(rawId);
            if (is != null) {
                byte[] buffer = new byte[128];
                int len = is.read(buffer); // 读取流内容
                if (len > 0) {
                    strData = new String(buffer, 0, len).trim(); // 生成字符串
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strData;
    }


    public static String getNameFromFilepath(String filepath) {
        int pos = filepath.lastIndexOf('/');
        if (pos != -1) {
            return filepath.substring(pos + 1);
        }
        return "";
    }

    public static void copy(String path, String targetPath) throws IOException {
        copy(new File(path), new File(targetPath));
    }

    /**
     * Copies a file.
     *
     * @param source The file which should be copied
     * @param target The file or directory to which the source-file should be
     *               copied to.
     * @throws FileNotFoundException when the source file was not found
     * @throws IOException           when there is an error while copying the file.
     */
    public static void copy(File source, File target) throws IOException {
        copy(source, target, new byte[64 * 1024]);
    }

    private static void copy(File source, File target, byte[] buffer) throws IOException {
        InputStream in = new FileInputStream(source);
        // create parent directory of target-file if necessary:
        File parent = target.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        if (target.isDirectory()) {
            target = new File(target, source.getName());
        }
        OutputStream out = new FileOutputStream(target);
        int read;
        try {
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            in.close();
            out.close();
        }
    }

    /**
     * 剔除后缀
     *
     * @param filename
     * @return
     */
    public static String cutSuffix(String filename) {
        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(0, dotPosition);
        }
        return filename;
    }

    /**
     * @param filename
     * @return
     */
    public static String getSuffix(String filename) {
        int dotPosition = filename.lastIndexOf('.');
        if (dotPosition != -1) {
            return filename.substring(dotPosition + 1, filename.length());
        }
        return "";
    }

    public static boolean isFileExist(String filePath) {
        boolean result = false;
        try {
            File e = new File(filePath);
            result = e.exists();
            e = null;
        } catch (Exception var3) {
            ;
        }
        return result;
    }


    public static void delFile(String filePath) {
        if (null != filePath) {
            File file = new File(filePath);
            if (file != null && file.exists()) {
                if (file.isFile()) {
                    file.delete();
                } else if (file.isDirectory()) {
                    File[] subFiles = file.listFiles();
                    int length = subFiles != null ? subFiles.length : 0;

                    for (int i = 0; i < length; ++i) {
                        File subFile = subFiles[i];
                        if (subFile.isDirectory()) {
                            delFile(subFile.getAbsolutePath());
                        }
                        subFile.delete();
                    }
                    file.delete();
                }
            }

        }
    }

    // url = file path or whatever suitable URL you want.
    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }


//    public static boolean isVideo(String uri) {
//        String type = getMimeType(uri);
//        if (!TextUtils.isEmpty(type)) {
//            Pattern pattern = Pattern.compile("^video/\\S*");
//            if (pattern.matcher(type).find()) {
//                return true;
//            }
//        }
//        return false;
//    }


//    public static boolean isPicture(String uri) {
//        String type = getMimeType(uri);
//        if (!TextUtils.isEmpty(type)) {
//            Pattern pattern = Pattern.compile("^image/\\S*");
//            if (pattern.matcher(type).find()) {
//                return true;
//            }
//        }
//        return false;
//    }

//    public static boolean isAudio(String uri) {
//        String type = getMimeType(uri);
//        if (!TextUtils.isEmpty(type)) {
//            Pattern pattern = Pattern.compile("^audio/\\S*");
//            if (pattern.matcher(type).find()) {
//                return true;
//            }
//        }
//        return false;
//    }

    /**
     * Check whether the file is a audio or not
     *
     * @param filename file
     * @return Returns true if the file is an Audio
     */
    public static boolean isAudio(String filename) {
        String ext = FilenameUtils.getExtension(filename).toLowerCase();
        if (TextUtils.isEmpty(ext)) {
            return false;
        }
        return ext.equals("flac")
                || ext.equals("mp3")
                || ext.equals("mid")
                || ext.equals("midi")
                || ext.equals("xmf")
                || ext.equals("mxmf")
                || ext.equals("rtttl")
                || ext.equals("rtx")
                || ext.equals("ota")
                || ext.equals("imy")
                || ext.equals("ogg")
                || ext.equals("aac");
    }

    /**
     * Check whether the file is a audio or not
     *
     * @param file file
     * @return Returns true if the file is an Audio
     */
    public static boolean isAudio(File file) {
        return isAudio(file.getAbsolutePath());
    }

    /**
     * Check whether the file is a video or not
     *
     * @param filename file path
     * @return Returns true if the file is an Video
     */
    public static boolean isVideo(String filename) {
        String ext = FilenameUtils.getExtension(filename).toLowerCase();
        return ext.equals("mkv")
                || ext.equals("avi")
                || ext.equals("mp4")
                || ext.equals("wmv")
                || ext.equals("3gp")
                || ext.equals("webm")
                || ext.equals("flv")
                || ext.equals("vob")
                || ext.equals("mov")
                || ext.equals("qt")
                || ext.equals("m4v")
                || ext.equals("mpg")
                || ext.equals("mpeg")
                || ext.equals("ts");
    }


    public static boolean isVideoExt(String ext) {
        if (TextUtils.isEmpty(ext)) {
            return false;
        }
        return ext.equals("mkv")
                || ext.equals("avi")
                || ext.equals("mp4")
                || ext.equals("wmv")
                || ext.equals("3gp")
                || ext.equals("webm")
                || ext.equals("flv")
                || ext.equals("vob")
                || ext.equals("mov")
                || ext.equals("qt")
                || ext.equals("m4v")
                || ext.equals("mpg")
                || ext.equals("mpeg")
                || ext.equals("ts");
    }

    /**
     * Check whether the file is a video or not
     *
     * @param file file
     * @return Returns true if the file is an Video
     */
    public static boolean isVideo(File file) {
        return isVideo(file.getAbsolutePath());
    }

    /**
     * Check whether the file is an image or not
     *
     * @param filename file path
     * @return Returns true if the file is an Image
     */
    public static boolean isImage(String filename) {
        String ext = FilenameUtils.getExtension(filename).toLowerCase();
        return ext.equals("jpg") || ext.equals("jpeg") || ext.equals("png") || ext.equals("bmp");
    }

    /**
     * Check whether the file is an image or not
     *
     * @param file file
     * @return Returns true if the file is an Image
     */
    public static boolean isImage(File file) {
        return isImage(file.getAbsolutePath());
    }

}
